package io.renren.modules.clearing.service.impl;

import cn.com.taiji.common.manager.net.http.binclient.ApiRequestException;
import cn.com.taiji.sdk.comm.LwClientHelper;
import cn.com.taiji.sdk.model.comm.protocol.cdts.passTransaction.ETCAccountTradeDisputeRecord;
import cn.com.taiji.sdk.model.comm.protocol.cdts.passTransaction.ETCAccountTradeUploadRequest;
import cn.com.taiji.sdk.model.comm.protocol.cdts.passTransaction.ETCAccountTradeUploadResponse;
import io.renren.common.utils.*;
import io.renren.modules.clearing.dao.ConfigParaDicDao;
import io.renren.modules.clearing.dao.DataExchangeListDao;
import io.renren.modules.clearing.dao.ETCAccountTradeUploadDao;
import io.renren.modules.clearing.entity.DataExchangeList;
import io.renren.modules.clearing.entity.tbl_ZFKExitWaste;
import io.renren.modules.clearing.service.ETCAccountTradeUploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.*;

@Service
public class ETCAccountTradeUploadServiceImpl implements ETCAccountTradeUploadService {

    private Logger log = LoggerFactory.getLogger(getClass());
    @Autowired
    ConfigParaDicDao configParaDicDao;
    @Autowired
    DataExchangeListDao dataExchangeListDao;

    @Autowired
    ETCAccountTradeUploadDao etcAccountTradeUploadDao;
    /**
     * ETC记账交易上传
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public List<DataExchangeList> ETCAUUpload() throws Exception {
        String msg="";
        List<DataExchangeList> dataList=null;
        //检查控制参数是否上传 tbl_configparadic
        log.info("开始检查控制参数");
        int control = configParaDicDao.checkContolParam(Constants.CONTROL_ETCAUDOWN_PARAM);
        if(control==1){
            //检查待上传的通知
            dataList = etcAccountTradeUploadDao.checkAccountTrade();
        }else{
            msg="接口暂停，任务退出";
            log.info(msg);
        }
        return dataList;
    }
    /**
     * 处理记账消息
     * @param data
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public boolean dealNotify(DataExchangeList data) throws Exception{
        boolean flag=false;

        //根据通知取出待记账数据
        List<tbl_ZFKExitWaste> list= new ArrayList<>();
        //检查是否记账完成
        list = etcAccountTradeUploadDao.checkAccountTrade(data);
        if(list!=null&&list.size()>0){
            log.info("服务方："+data.getSenderID()+"交易包号："+data.getMessageID()+"记账通知对应交易明细有未记账数据");
            return false;
        }
        list = etcAccountTradeUploadDao.getAccountTradeData(data);
        ETCAccountTradeUploadRequest request = new ETCAccountTradeUploadRequest();
        //确认记账总记录数量
        int accountCount=0;
        //确认记账总金额
        long accountAmount=0;
        //本记账文件包含的争议交易数量
        int disputedCount=0;

        if(list!=null&&list.size()>0){
            List<ETCAccountTradeDisputeRecord> disputedRecord = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getValidFlag()==0) {
                    Double tempFee=list.get(i).getStoreMoney()+list.get(i).getTallyMoney();
                    accountCount++;
                    accountAmount+=tempFee.intValue();
                }else{
                    ETCAccountTradeDisputeRecord etcAccountTradeDisputeRecord = new ETCAccountTradeDisputeRecord();
                    etcAccountTradeDisputeRecord.setId(list.get(i).getKeyPressInfo());
                    etcAccountTradeDisputeRecord.setResult(list.get(i).getValidFlag().intValue());
                    disputedRecord.add(etcAccountTradeDisputeRecord);
                    disputedCount++;
                }
            }
            request.setIssuerId(data.getReceiverID());
            request.setTollProvinceId(data.getSenderID());
            request.setMessageId(Long.parseLong(data.getMessageID()));
            request.setProcessTime(DateUtil.formatDateTimes(new Date()));
            request.setCount(list.size());
            request.setAccountCount(accountCount);
            //	request.setAccountAmount(accountAmount);
            request.setAccountAmount(accountAmount);
            request.setDisputedCount(disputedCount);
            request.setDisputedRecord(disputedRecord);
            //if(disputedCount>0){
            //	request.setDisputedRecord(disputedRecord);
            //	}

            request.setReqSender(Config.issuerId);

            log.info(request.toJson());
            try {
                ETCAccountTradeUploadResponse response = LwClientHelper.binPostUrl(request);

                if(response!=null&&response.getInfo().equals("成功！")){
                    log.info("服务方："+data.getSenderID()+"交易包号："+data.getMessageID()+"记账结果上传成功："+response.toJson());
                    Date nowTime= DateUtil.formatDateTime6(response.getReceiveTime());
                    data.setReplyTime(nowTime);

                    //修改流水记账信息
                    etcAccountTradeUploadDao.EditZfkWasteChargefalg(data);
                    //sqlMapClient.update("ZfkExitW_ORACLE.EditZfkWasteChargefalg",data);

                    //更新通知信息
                    dataExchangeListDao.editDataChangeListReplag(data);
                    //sqlMapClient.update("Base_ORACLE.editDataChangeListReplag",data);

                    //Tbl_DataExchangeList插入
                    DataExchangeList dataExchangeList= addDataExchangeList(data, request);
                    dataExchangeListDao.addDataExchangeList(dataExchangeList);
                    //sqlMapClient.insert("Base_ORACLE.addDataExchangeList",dataExchangeList);
                    //插入日志表
                   // DataExchangeLog dataLog = addLog(request, 1,"记账交易上传成功");
                   // sqlMapClient.insert("Base_ORACLE.addDataExchangeLog",dataLog);

                }else{
                    log.info("响应失败："+response.toJson());
                }
            } catch (IOException e) {
                e.printStackTrace();
                //失败插入日志表
               // DataExchangeLog dataLog = addLog(request, 0,"记账交易上传失败");
                //sqlMapClient.insert("Base_ORACLE.addDataExchangeLog",dataLog);

            } catch (ApiRequestException apie) {
                apie.printStackTrace();
                log.error("错误码："+apie.getErrCode()+" 错误信息："+apie.getMessage());
                //失败插入日志表
               // DataExchangeLog dataLog = addLog(request, 0, apie.getMessage());
               // sqlMapClient.insert("Base_ORACLE.addDataExchangeLog",dataLog);
            }catch (Exception e) {
                //String msg= e.getMessage().length()>=500?e.getMessage().substring(0, 500):e.getMessage();
                String msg=TypeTransUtil.getErrorMessage(e.getMessage()) ;
                throw new Exception("ETC记账上传请求响应失败服务方:"+data.getSenderID()+"包号："+data.getMessageID()+msg);
            }

        }else{
            log.info("记账通知无对应交易明细，继续执行");
            return false;
        }
        return flag;

    }
    /**
     * 添加全国联网记录
     * @param data
     * @param request
     * @return
     * @throws Exception
     */
    public DataExchangeList addDataExchangeList(DataExchangeList data,ETCAccountTradeUploadRequest request)throws Exception{
        DataExchangeList dataExchangeList= new DataExchangeList();
        dataExchangeList.setMessageID(data.getMessageID());
        dataExchangeList.setSenderID(Config.issuerId);
        dataExchangeList.setReceiverID(data.getSenderID());
        dataExchangeList.setProcessTime(data.getReplyTime());
        dataExchangeList.setMessageClass(1);
        dataExchangeList.setMessageType(5);
        dataExchangeList.setContentType(1);
        dataExchangeList.setResult(1);
        dataExchangeList.setRecCount(request.getCount());
        dataExchangeList.setRecAmount(request.getAccountAmount());
        dataExchangeList.setVersion(0);
        dataExchangeList.setReplyFlag(1);
        dataExchangeList.setReplyTime(data.getReplyTime());
        dataExchangeList.setFileName(request.getFilename());
        dataExchangeList.setResultDesc("ETC记账交易上传成功");
        dataExchangeList.setSpare1(data.getMessageID());
        dataExchangeList.setSpare3("ETC记账交易上传成功");
        return dataExchangeList;

    }


}
